package com.cuoyi.coupon.mall.manager;

import com.cuoyi.coupon.mall.common.BusinessException;
import com.cuoyi.coupon.mall.constant.ImageConstant;
import com.cuoyi.coupon.mall.enums.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author zhang.cheng
 * 2022-02-17 14:33
 **/

@Service
@Slf4j
public class ImageManager {

    /**
     * 将文件写入到本地
     * getOriginalFilename：获取上传时的文件名
     * getName：获取表单中文件组件的名字
     */
    public String uploadImage(MultipartFile file) {
        FileOutputStream out = null;
        try {
            byte[] bytes = file.getBytes();
            String path = ImageConstant.DIR_PRO + file.getOriginalFilename();
            File newFile = new File(path);
            out = new FileOutputStream(newFile);
            out.write(bytes);
            out.flush();
            return String.format(ImageConstant.GET_IMAGE_URL_PRO, file.getOriginalFilename());
        } catch (IOException e) {
            log.error("uploadImage error......", e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                log.error("uploadImage error......", e);
            }
        }
        return "";
    }

    /**
     * 从本地读取文件并返回到网页中
     */
    public void getImage(String filename, HttpServletResponse response) {
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            File file = new File(ImageConstant.DIR_PRO + filename);
            in = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] bytes = new byte[1024 * 10];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            throw new BusinessException(ErrorEnum.SYSTEM_ERROR.code(), "图片不存在");
        } finally {
            try {
                in.close();
                out.close();
            } catch (Exception e) {
                throw new BusinessException(ErrorEnum.SYSTEM_ERROR.code(), "图片不存在");
            }
        }
    }
}
